﻿using Qy.Core;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class AttmentService : QyRepository<Attment>
{
    public AttmentService(ApplicationContext applicationContext) : base(applicationContext) { }

    public async Task<PagedInfo<ViewAttment>> GetPageListAsync(AttmentQuery parm)
    {

        DateTime startDate = DateUtility.GetBeginTime(parm.StartDate, -1);
        DateTime endDate = DateUtility.GetBeginTime(parm.EndDate, 1);

        var exp = Expressionable.Create<Attment>();
        exp = exp.AndIF(parm.Uid != 0, att => att.Uid == parm.Uid);
        exp = exp.AndIF(parm.StartDate != null && parm.EndDate != null, att => att.Time >= startDate && att.Time <= endDate);

        return await Queryable()
            .LeftJoin<User>((att, user) => att.Uid == user.Id)
            .LeftJoin<UserDept>((att, user, dept) => user.DeptId == dept.Id)
            .Where(exp.ToExpression())
            .WhereIF(!string.IsNullOrEmpty(parm.NickName), (att, user, dept) => user.NickName.Contains(parm.NickName))
            .OrderBy((att) => att.Id, OrderByType.Desc)
            .Select((att, user, dept) => new ViewAttment()
            {
                NickName = user.NickName,
                DeptName = dept.Name
            }, true)
            .ToPageAsync(parm);
    }

    public async Task<List<Attment>> GetListAsync(List<int> attIds)
    {
        return await Queryable()
                  .Where(it => attIds.Contains(it.Id))
                  .OrderBy(it => new { it.Id, it.Uid })
                  .ToListAsync();
    }

}
